package com.jilian.mydemo.modul.my.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.common.dto.VideoArticlesDto;
import com.jilian.mydemo.common.dto.VideoArticlesListDto;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.exam.ui.ArticleCetailsActivity;
import com.jilian.mydemo.modul.exam.ui.VideoDetailsActivity;
import com.jilian.mydemo.modul.my.adapter.ClassRoomAdapter;
import com.jilian.mydemo.modul.my.adapter.MyCollectionAdapter;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.BtiMapUtils;
import com.jilian.mydemo.utils.EmptyUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 我的收藏
 */
public class MyCollectionActivity extends BaseActivity implements CustomItemClickListener {
    //
    private RecyclerView recyclerview;
    //
    private ClassRoomAdapter adapter;
    //
    private List<VideoArticlesDto> datas;
    //
    private LinearLayoutManager linearLayoutManager;
    //
    private UserViewModel userViewModel;
    //
    private SmartRefreshLayout srHasData;
    //
    private SmartRefreshLayout srNoData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }


    @Override
    protected void createViewModel() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_mycollection;
    }

    @Override
    public void initView() {
        setNormalTitle("我的收藏", v -> finish());
        srHasData = (SmartRefreshLayout) findViewById(R.id.sr_has_data);
        srNoData = (SmartRefreshLayout) findViewById(R.id.sr_no_data);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(this);
        datas = new ArrayList<>();
        recyclerview.setLayoutManager(linearLayoutManager);
        adapter = new ClassRoomAdapter(this, datas, this);
        recyclerview.setAdapter(adapter);
        srNoData.setEnableLoadMore(false);
    }

    @Override
    public void initData() {
        showLoadingDialog();
        queryCollect();
    }

    @Override
    public void initListener() {
        RxBus.getInstance().toObservable().map(new Function<Object, BaseEventMsg>() {
            @Override
            public BaseEventMsg apply(Object o) throws Exception {
                return (BaseEventMsg) o;
            }
        }).subscribe(new Consumer<BaseEventMsg>() {
            @Override
            public void accept(BaseEventMsg eventMsg) throws Exception {
                if (eventMsg != null && eventMsg.getCollectRefreshDto() != null) {
                    if (eventMsg.getCollectRefreshDto().getCode() == 100) {
                        pageNum = 1;
                        queryCollect();
                    }
                }
            }
        });
        srHasData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                queryCollect();
            }
        });
        srHasData.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                queryCollect();
            }
        });
        srNoData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                queryCollect();
            }
        });
    }

    private Integer pageNum = 1;//
    private Integer pageSize = 20;//
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1000) {
                List<VideoArticlesDto> list = (List<VideoArticlesDto>) msg.obj;
                datas.clear();
                datas.addAll(list);
                adapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 查询我 收藏
     */
    private void queryCollect() {
        userViewModel.queryCollect(pageNum, pageSize);
        userViewModel.getCollectListliveData().observe(this, new Observer<BaseDto<VideoArticlesListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<VideoArticlesListDto> dto) {
                hideLoadingDialog();
                srNoData.finishRefresh();
                srHasData.finishRefresh();
                srHasData.finishLoadMore();
                //有数据
                if (dto.isSuccess() && EmptyUtils.isNotEmpty(dto.getData().getList())) {
                    srNoData.setVisibility(View.GONE);
                    srHasData.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        datas.clear();
                    }
                    datas.addAll(dto.getData().getList());
                    adapter.notifyDataSetChanged();
                    //开启子线程
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            //对视频封面处理 耗时操作
                            for (int i = 0; i < dto.getData().getList().size(); i++) {
                                if (dto.getData().getList().get(i).getType() == 2 && !TextUtils.isEmpty(dto.getData().getList().get(i).getPath())) {
                                    dto.getData().getList().get(i).setBitmap(BtiMapUtils.getNetVideoBitmap(dto.getData().getList().get(i).getPath()));
                                }
                            }
                            Message msg = Message.obtain();
                            msg.what = 1000;
                            msg.obj = dto.getData().getList();
                            handler.sendMessage(msg);
                        }
                    }.start();

                } else {
                    hideLoadingDialog();
                    //说明是上拉加载
                    if (pageNum > 1) {
                        pageNum--;
                    } else {
                        //第一次就没数据
                        srNoData.setVisibility(View.VISIBLE);
                        srHasData.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        if (datas.get(position).getId() == null) {
            return;
        }

        Intent intent = new Intent(this, ArticleCetailsActivity.class);
        intent.putExtra("id", String.valueOf(datas.get(position).getId()));
        intent.putExtra("title", datas.get(position).getTitle());
        intent.putExtra("param", "1");
        startActivity(intent);


    }


}
